// background.js - Chrome扩展后台脚本

// 监听扩展安装事件
chrome.runtime.onInstalled.addListener(() => {
  console.log('TigerDict extension installed');

  // 初始化存储
  chrome.storage.local.set({
    youdaoAppKey: '',
    youdaoSecret: '',
    tigerDeckApiKey: '',
  });
});

// 监听扩展启动事件
chrome.runtime.onStartup.addListener(() => {
  console.log('TigerDict extension started');
});

// SHA256加密函数
async function sha256(message) {
  // 使用Web Crypto API进行SHA256加密
  const msgBuffer = new TextEncoder().encode(message);
  const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
}

// 生成有道API签名
async function generateSign(query, appKey, salt, curtime, secretKey) {
  // 根据有道API文档，signType=v3时签名规则为：
  // sha256(应用ID+input+salt+curtime+应用密钥)
  // input为：q的前10个字符 + q的长度 + q的后10个字符(当q长度大于20)或q字符串(当q长度小于等于20)

  let input = query;
  if (query.length > 20) {
    input =
      query.substring(0, 10) +
      query.length +
      query.substring(query.length - 10);
  }

  const str = appKey + input + salt + curtime + secretKey;
  return await sha256(str);
}

// 监听来自content script的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'translate') {
    handleTranslation(request.data)
      .then((result) => sendResponse({ data: result }))
      .catch((error) => sendResponse({ error: error.message }));
    return true; // 保持消息通道开放以进行异步响应
  }

  if (request.action === 'addWordToTigerDeck') {
    addWordToTigerDeck(request.data)
      .then((result) => sendResponse({ result }))
      .catch((error) => sendResponse({ error: error.message }));
    return true; // 保持消息通道开放以进行异步响应
  }
});

// 处理翻译请求
async function handleTranslation(data) {
  const { text, appKey, secret } = data;

  // 构造有道翻译API请求
  const salt = Date.now().toString(); // 随机数
  const curtime = Math.floor(Date.now() / 1000).toString(); // 当前UTC时间戳(秒)
  const sign = await generateSign(text, appKey, salt, curtime, secret);

  const params = new URLSearchParams();
  params.append('q', text);
  params.append('from', 'auto');
  params.append('to', 'zh-CHS');
  params.append('appKey', appKey);
  params.append('salt', salt);
  params.append('sign', sign);
  params.append('signType', 'v3');
  params.append('curtime', curtime);

  // 实际调用有道翻译API
  const response = await fetch('https://openapi.youdao.com/api', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: params,
  });

  return await response.json();
}

// 添加单词到 TigerDeck
async function addWordToTigerDeck(data) {
  const { question, answer } = data;

  try {
    // 从存储中获取 TigerDeck API Key
    const { tigerDeckApiKey } = await chrome.storage.local.get([
      'tigerDeckApiKey',
    ]);

    if (!tigerDeckApiKey) {
      throw new Error('请先在扩展设置中配置 TigerDeck API Key');
    }

    // 发送请求到 TigerDeck
    const response = await fetch('http://localhost:2022/api/decks/cards/open', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        openToken: tigerDeckApiKey,
        question: question,
        answer: answer,
      }),
    });

    if (!response.ok) {
      throw new Error('添加失败: ' + response.status);
    }

    return { success: true };
  } catch (error) {
    console.error('添加单词到 TigerDeck 失败:', error);
    throw error;
  }
}
